package com.laiyw.monitor.core.http;

import com.alibaba.fastjson.JSON;
import com.laiyw.monitor.core.commons.Constants;
import com.laiyw.monitor.core.context.InvokeInfo;

import javax.servlet.ServletContext;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Description:
 * @Auther: Laiyw
 * @Date: 2018/10/3 23:20
 */
public class MonitorServlet extends ResourceServlet {

    private ServletContext servletContext;

    public MonitorServlet() {
        super("http");
    }

    @Override
    protected String process(String url, ServletContext sc) {
        try {
            servletContext = sc;
            InvokeInfo invokeInfo = getInvokeInfo(url);
            if (null == invokeInfo)
                return null;
            return JSON.toJSONString(invoke(invokeInfo));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Object invoke(InvokeInfo invokeInfo) throws IllegalAccessException, InstantiationException, InvocationTargetException {
        return invokeInfo.getMethod().invoke(invokeInfo.getInstance(), invokeInfo.getParameters());
    }

    private InvokeInfo getInvokeInfo(String url) {
        Map<String, InvokeInfo> controllerMap = getControllerMap();
        if (null == controllerMap || controllerMap.isEmpty())
            return null;
        InvokeInfo invokeInfo = controllerMap.get(url);
        if (null == invokeInfo)
            return null;
        return invokeInfo;
    }

    private Map<String, InvokeInfo> getControllerMap() {
        return (Map<String, InvokeInfo>) servletContext.getAttribute(Constants.MONITOR_REQUEST_MAP);
    }

}
